<template>
  <el-card shadow="never">
    <template #header>
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="6" :xs="24">
            <el-form-item label="广告名称">
              <el-input v-model="page.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="广告类型">
              <el-select v-model="page.type" style="width: 100%" clearable>
                <el-option v-for="item in advertTypeList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" :xs="24">
            <el-form-item label="广告状态">
              <el-select v-model="page.status" style="width: 100%" clearable>
                <el-option v-for="item in advertStatusList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="贷超APP">
            <el-select v-model="page.appId" clearable>
              <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                         :value="item.appId"></el-option>
            </el-select>
          </el-form-item>
          <el-col :span="10" :xs="24">
            <el-form-item label="起止时间">
              <el-date-picker
                  v-model="page.timeValue"
                  style="width: 100%"
                  type="daterange"
                  range-separator="~"
                  value-format="x"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6" :xs="24">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getTableData">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <el-button type="danger" @click="batchDeleteList" v-permiss="['list-batchdel']">批量删除</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="addAdvert" v-permiss="['list-add']">添加广告</el-button>
    </div>
    <Table :tableColumn="tableColumn" :page="page" :tableData="tableData" :selection="true"
           :selectRows="advertSelectionRows"
           :loading="loading"
           @handleSelectionChange="(val)=>{advertSelectionRows = val}"
           @handleCurrentChange="(val)=>{page.pageNum = val,getTableData()}"
           @handleSizeChange="(val)=>{page.pageSize = val,getTableData()}"
    >
      <template #type="{row}">
        {{ advertTypeList.find(item => item.value === row.type).label || '' }}
      </template>
      <template #status="{row}">
        {{ advertStatusList.find(item => item.value === row.status).label || '' }}
      </template>
      <template #activityStartTime="{row}">
        {{ row.activityStartTime }} ~ {{ row.activityEndTime }}
      </template>
      <template #img="{row}">
        <el-image style="width: 80px;height: 80px" v-if="row.img" :preview-src-list="[row.img]"
                  :src="row.img"></el-image>
      </template>
      <template #handle="{row}">
        <el-button type="text" v-permiss="['list-change']" @click="changeAdvertStatus(row,'put')">{{
            row.status === 1 || row.status === 3 ? '上架' : '下架'
          }}
        </el-button>
        <el-button type="text" @click="editAdvert(row)" v-permiss="['list-edit']">编辑</el-button>
        <el-button type="text" @click="selectProduct(row)" v-if="row.type === 2" v-permiss="['bind-search']">选择产品
        </el-button>
        <el-button type="text" @click="changeAdvertStatus(row,'del')" v-show="row.status === 1 || row.status === 3"
                   v-permiss="['list-del']">删除
        </el-button>
      </template>
    </Table>
    <!--    广告添加编辑-->
    <Dialog v-model="advertVisible.isShow"
            :title="advertVisible.title"
            :footer="advertVisible.type !== 'edit' || advertForm.status !== 2"
            @cancel="advertVisible.isShow = false"
            @close="clearAdvertForm"
            @confirm="advertFormConfirm"
    >
      <el-form label-width="80px" :model="advertForm" :rules="advertRulesForm" ref="advertFormRef">
        <el-form-item label="广告类型" prop="type">
          <el-select style="width: 100%" v-model="advertForm.type">
            <el-option v-for="item in advertTypeList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="advertForm.name"/>
        </el-form-item>
        <el-form-item label="所属贷超APP" prop="appId" label-width="120px">
          <el-select v-model="advertForm.appId" :disabled="advertVisible.type === 'edit'  &&  advertForm.type === 2">
            <el-option v-for="item in productList" :key="item.appId" :label="item.appName"
                       :value="item.appId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跳转链接" prop="url" v-if="advertForm.type === 1">
          <el-input v-model="advertForm.url"/>
        </el-form-item>
        <el-form-item label="广告描述" prop="description">
          <el-input type="textarea" v-model="advertForm.description" :rows="3"/>
        </el-form-item>
        <el-form-item label="广告图片" prop="img">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              ref="upload"
              :http-request="uploadChange"
              accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
          >
            <i v-if="!advertForm.img" class="el-icon-plus avatar-uploader-icon"></i>
            <img v-else style="width: 100%;height: 100%" :src="advertForm.img">
          </el-upload>
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
              v-model="advertForm.activityTime"
              style="width: 100%"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    未绑定产品-->
    <Dialog v-model="productVisible.isShow"
            @confirm="productConfirm"
            width="66%"
            @close="clearProduct"
            :title="productVisible.title"
            @cancel="productVisible.isShow = false">
      <el-form label-width="80px">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="产品名称">
              <el-input v-model="productPage.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属机构">
              <el-select v-model="productPage.institutionId" style="width: 100%" clearable>
                <el-option v-for="item in institutionSelect" :key="item.institutionId" :value="item.institutionId"
                           :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label-width="20px">
              <el-button type="primary" @click="getProduct">查询</el-button>
              <el-button @click="productResetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <Table :tableColumn="productColumn" :tableData="productData" :page="false" maxHeight="600px"
      >
        <template #logoUrl="{row}">
          <el-image v-if="row.logoUrl" style="width: 150px;height: 150px" :src="row.logoUrl"
                    :preview-src-list="[row.logoUrl]"></el-image>
        </template>
        <template #feeStage="{row}">
          {{ row.feeStage === 1 ? 'CPA订单量' : 'CPS放款量' }}
        </template>
        <template #loanMaxLimit="{row}">
          {{ row.loanMinLimit }} - {{ row.loanMaxLimit }}
        </template>
        <template #radio="{row}">
          <el-radio v-model="bindProduct.productId" :label="row.productId"><span></span></el-radio>
        </template>
      </Table>
    </Dialog>
  </el-card>
</template>

<script>
import {ref, reactive, defineComponent, onMounted, toRefs} from "vue";
import {
  fetchAdvert,
  updateAdvertisementStatus,
  increaseAdvert,
  batchDeleteAdvert,
  fetchBindProduct,
  advertBindProduct,
} from '@/api/homeManage'
import {selectInstitution, selectProductList, uploadImage} from '@/api/index'
import {ElMessage, ElMessageBox} from "element-plus";
import {dateFormatTimeStamp} from '@/utils/index'

const tableColumn = [
  {label: '广告图片', slot: 'img', align: 'center', minWidth: 100},
  {label: '广告名称', prop: 'name', align: 'center', minWidth: 150},
  {label: '广告类型', slot: 'type', align: 'center', minWidth: 100},
  {label: '跳转页面', prop: "url", align: "center", minWidth: 200,},
  {label: '起止时间', prop: 'activityStartTime', slot: 'activityStartTime', align: 'center', minWidth: 300},
  {label: '状态', slot: 'status', align: 'center', minWidth: 150},
  {label: '描述', prop: 'description', align: 'center', minWidth: 150},
  {label: '贷超APP', prop: 'appName', align: 'center', minWidth: 100},
  {label: '创建时间', prop: 'creationTime', align: 'center', minWidth: 150},
  {label: '创建人', prop: 'createName', align: 'center', minWidth: 150},
  {label: '操作', slot: 'handle', align: 'center', fixed: 'right', minWidth: 200},
]
const productColumn = [
  {label: '', align: 'center', slot: 'radio', minWidth: 55},
  {label: '产品名称', prop: 'productName', align: 'center'},
  {label: '所属机构', prop: 'name', align: 'center'},
  {label: '产品logo', prop: 'logoUrl', slot: 'logoUrl', align: 'center', minWidth: 100},
  {label: '可贷范围', prop: 'loanMaxLimit', slot: 'loanMaxLimit', align: 'center'},
  {label: '收费方式', prop: 'feeStage', slot: 'feeStage', align: 'center'},
]
export default defineComponent({
  name: "AdvertList",
  setup() {
    const advertFormRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      productPage: {
        pageNum: 1,
        pageSize: 1000,
        total: 0,
      },
      advertStatusList: [
        {label: '待上架', value: 1},
        {label: '已上架', value: 2},
        {label: '已下架', value: 3},
      ],
      advertTypeList: [
        {label: '图片', value: 0},
        {label: '外链', value: 1},
        {label: '机构产品', value: 2},
      ],
      advertVisible: {
        isShow: false,
        title: '新增广告',
        type: 'add'
      },
      tableData: [],
      loading: false,
      advertForm: {
        type: null
      },
      advertRulesForm: {
        name: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        url: [
          {required: true, message: '不能为空', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择广告类型', trigger: 'change'}
        ],
        activityTime: [
          {required: true, message: '请选择时间', trigger: 'blur'}
        ],
        img: [
          {required: true, message: '请上传活动图片', trigger: 'change'}
        ],
        appId: [
          {required: true, message: '请选择APP', trigger: 'change'}
        ]
      },
      advertSelectionRows: [],
      productVisible: {
        isShow: false,
        title: '新增广告',
        type: 'add'
      },
      advertRows: {},
      productData: [],
      bindProduct: {
        productId: null
      },
      productList: [],
      institutionSelect: []
    })
    const methods = {
      async getTableData() {
        state.loading = true
        const [activityStartTime, activityEndTime] = dateFormatTimeStamp(state.page.timeValue)
        const params = {
          ...state.page,
          activityStartTime, activityEndTime
        }
        const res = await fetchAdvert(params)
        if (res.code === 200) {
          state.loading = false
          const {list, total} = res.data
          state.tableData = list
          state.page = {
            ...state.page,
            total
          }
        } else {
          state.loading = false
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0,
        }
        methods.getTableData()
      },
      // 选择产品
      selectProduct(row) {
        state.productVisible = {
          isShow: true,
          title: row.name + ' - ' + '未绑列表',
          type: 'add'
        }
        state.advertRows = {...row}
        methods.getSelect()
        methods.getProduct()
      },
      clearProduct() {
        state.productPage = {
          pageNum: 1,
          pageSize: 1000,
          total: 0,
        }
        state.bindProduct.productId = null
      },
      getSelect() {
        selectInstitution().then(res => {
          state.institutionSelect = res.data
        })
      },
      async getProduct() {
        const res = await fetchBindProduct({
          bannerId: state.advertRows.id,
          appId: state.advertRows.appId,
          ...state.productPage
        })
        if (res.code === 200) {
          state.productData = res.data
          const isBind = res.data.filter(item => item.isOk === 1)
          if (isBind.length > 0) {
            state.bindProduct.productId = isBind[0].productId
          }
        }
      },
      async uploadChange(data) {
        const formData = new FormData()
        formData.append('file', data.file)
        formData.append('type', 1)
        const res = await uploadImage(formData)
        if (res.code === 200) {
          state.advertForm.img = res.data
        }
      },
      // 绑定产品重置
      productResetSearch() {
        state.productPage = {
          pageNum: 1,
          pageSize: 1000,
          total: 0,
        }
        methods.getProduct()
      },
      // 绑定产品提交
      async productConfirm() {
        const {id} = state.advertRows
        const {productId} = state.bindProduct
        const params = {
          bannerId: id,
          proId: productId
        }
        const res = await advertBindProduct(params)
        if (res.code === 200) {
          state.productVisible.isShow = false
          ElMessage.success('绑定成功')
          methods.getTableData()
        }
      },
      clearAdvertForm() {
        state.advertForm = {}
        advertFormRef.value.resetFields()
      },
      // 添加、编辑广告提交
      advertFormConfirm() {
        advertFormRef.value.validate(async v => {
          if (v) {
            const api = ((params) => state.advertVisible.type === 'add' ? increaseAdvert(params) : updateAdvertisementStatus(params))
            const [activityStartTime, activityEndTime] = state.advertForm.activityTime || []
            const params = {
              ...state.advertForm,
              activityStartTime, activityEndTime,
              appName: state.productList.find(p => state.advertForm.appId === p.appId).appName
            }
            delete params.activityTime
            const res = await api(params)
            if (res.code === 200) {
              ElMessage.success({
                message: state.advertVisible.type === 'add' ? '添加成功' : '编辑成功'
              })
              state.advertVisible.isShow = false
              methods.getTableData()
            }
          }
        })
      },
      // 编辑广告
      editAdvert(row) {
        const {activityStartTime, activityEndTime,} = row
        state.advertForm = {...row, activityTime: [activityStartTime, activityEndTime]}
        state.advertVisible = {
          isShow: true,
          title: row.name + ' - ' + '编辑广告',
          type: 'edit'
        }
      },
      // 添加广告
      addAdvert() {
        state.advertVisible = {
          isShow: true,
          title: '新增广告',
          type: 'add'
        }
      },
      // 批量删除
      batchDeleteList() {
        if (state.advertSelectionRows.length <= 0) return ElMessage.error('请先勾选要删除的广告')
        ElMessageBox.confirm('确认删除?', '提示', {
          type: 'warning',
        }).then(async () => {
          const ids = state.advertSelectionRows.map(item => {
            return {
              id: item.id,
              status: 0
            }
          })
          const res = await batchDeleteAdvert(ids)
          if (res.code === 200) {
            ElMessage.success('删除成功')
            methods.getTableData()
          }
        }).catch(() => {

        });
      },
      // 上下架 删除
      changeAdvertStatus(row, type) {
        ElMessageBox.confirm('确认进行此操作?', '提示', {
          type: 'warning',
        }).then(async () => {
          const params = {
            id: row.id
          }
          if (type === 'del') {
            params.status = 0
          } else {
            // 待上架 || 下架
            if (row.status === 1 || row.status === 3) {
              params.status = 2
            } else {
              // 已上架
              params.status = 3
            }
          }
          const res = await updateAdvertisementStatus(params)
          if (res.code === 200) {
            ElMessage.success({
              message: '操作成功'
            })
            methods.getTableData()
          }
        }).catch(() => {

        });
      },

    }
    onMounted(() => {
      methods.getTableData()
      selectProductList().then(res => {
        if (res.code === 200) {
          state.productList = res.data
        }
      })
    })
    return {
      advertFormRef,
      close,
      tableColumn,
      ...toRefs(state),
      ...methods,
      productColumn
    }
  }
})
</script>

<style scoped>

</style>
